import { ref, reactive } from 'vue'
import { roleApi } from '@/api/modules/system/role'
import type { Role } from '@/api/modules/system/role'

export function useRole() {
  const filters = {
    roleType: [
      { text: '自定义角色', value: '1' },
      { text: '系统角色', value: '0' }
    ],
    roleStatus: [
      { text: '启用', value: '1' },
      { text: '禁用', value: '0' }
    ]
  }

  const formatRoleType = (val: number) => {
    if (val === 0) {
      return '系统角色'
    } else if (val === 1) {
      return '自定义角色'
    }
  }
  const formatRoleStatus = (val: number) => {
    if (val === 1) {
      return '启用'
    } else {
      return '禁用'
    }
  }

  const handleFormatter = (row: any, column: any, cellValue: any) => {
    if (column.property === 'roleType') {
      return formatRoleType(cellValue)
    } else if (column.property === 'roleStatus') {
      return formatRoleStatus(cellValue)
    }
  }

  const statusData = reactive({} as { [key: string]: number })
  const refTable = ref()
  const tableData = reactive({ resp: { list: [], total: 0 }, loading: false })
  const handleQuery = (page: AxiosType.Pagination) => {
    tableData.loading = true
    roleApi.findListPage(page).then(resp => {
      if (resp.success) {
        tableData.resp = resp.data
        resp.data.list.forEach((r: Role) => {
          statusData[r.roleId] = r.roleStatus
        })
      }
      tableData.loading = false
    })
  }

  return { refTable, tableData, statusData, handleQuery, filters, handleFormatter }
}
